// Practice module

// State variables
let currentType = localStorage.getItem('practiceType') || 'sentences'; // 'words' or 'sentences'
let practiceData = null;
let shuffledWords = [];
let shuffledSentences = []; 
let practiceIndex = 0;
let currentText = '';
let userInput = '';

// DOM elements
let practiceTextDisplayElement = null;
let typingAreaElement = null;
let practiceTypeSelectElement = null;

// Helper function to shuffle an array (Fisher-Yates Algorithm)
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]]; // Swap elements
    }
    return array; // modify in place
}

// Initialize practice data from window.practiceData
function initializePracticeData() {
    try {
        practiceData = window.practiceData;
        if (!practiceData) {
            throw new Error('Practice data not loaded');
        }
        
        // Shuffle data upon loading
        if (practiceData.words) {
            shuffledWords = shuffleArray([...practiceData.words]); // Copy and shuffle
        }
        if (practiceData.sentences) {
            shuffledSentences = shuffleArray([...practiceData.sentences]); // Copy and shuffle
        }
        practiceIndex = 0; // Reset index whenever data is loaded/shuffled
        
        updatePracticeContent();
    } catch (error) {
        console.error('Error initializing data:', error);
        if (practiceTextDisplayElement) {
             practiceTextDisplayElement.textContent = 'Error loading practice data.';
        }
    }
}

// Update practice content display
function updatePracticeContent() {
    if (!practiceTextDisplayElement || !typingAreaElement) return;

    if (currentType === 'random') {
        practiceTextDisplayElement.style.display = 'none';
        typingAreaElement.classList.remove('rounded-b-2xl');
        typingAreaElement.classList.add('rounded-2xl');
        typingAreaElement.value = '';
        typingAreaElement.placeholder = 'بۇ يەرگە يېزىڭ...';
        currentText = '';
        userInput = '';
        practiceIndex = 0; // Reset index for random type
    } else {
        practiceTextDisplayElement.style.display = 'block';
        typingAreaElement.classList.remove('rounded-2xl');
        typingAreaElement.classList.add('rounded-b-2xl');
        typingAreaElement.placeholder = 'ئۈستىدىكى ئۈلگە تېسكىتنى كىرگۈزۈپ مەشىقنى باشلاڭ...';

        let contentList = [];
        if (currentType === 'words') {
            contentList = shuffledWords;
        } else if (currentType === 'sentences') {
            contentList = shuffledSentences;
        }

        if (!contentList || contentList.length === 0) {
            console.error(`No shuffled content available for type: ${currentType}`);
            practiceTextDisplayElement.textContent = `No practice content available for ${currentType}.`;
            typingAreaElement.value = '';
            currentText = '';
            userInput = '';
            practiceIndex = 0;
            return;
        }

        // Check if we need to reshuffle and reset index
        if (practiceIndex >= contentList.length) {
            if (currentType === 'words') {
                shuffledWords = shuffleArray([...practiceData.words]); // Reshuffle
            } else if (currentType === 'sentences') {
                shuffledSentences = shuffleArray([...practiceData.sentences]); // Reshuffle
            }
            practiceIndex = 0; // Reset index
            contentList = (currentType === 'words') ? shuffledWords : shuffledSentences; // Update contentList reference
        }

        currentText = contentList[practiceIndex];
        practiceIndex++; // Move to the next text
        userInput = '';

        // Display the practice text
        practiceTextDisplayElement.innerHTML = currentText;
        typingAreaElement.value = '';
    }
}

// Check user input against the displayed practice text
function checkTyping() {
    if (!typingAreaElement || !practiceTextDisplayElement || currentType === 'random') return;

    userInput = typingAreaElement.value;
    
    // Create HTML for displaying the text with colors
    let displayHTML = '';
    for (let i = 0; i < currentText.length; i++) {
        if (i < userInput.length) {
            // ئىشلەتكۈچى كىرگۈزگەن ھەرپلەر
            if (userInput[i] === currentText[i]) {
                // توغرا ھەرپلەر يېشىل رەڭدە
                displayHTML += `<span class="text-green-700">${currentText[i]}</span>`;
            } else {
                // خاتا ھەرپلەر قىزىل رەڭدە
                displayHTML += `<span class="text-red-500">${currentText[i]}</span>`;
            }
        } else {
            // ئىشلەتكۈچى تېخى كىرگۈزمىگەن ھەرپلەر
            displayHTML += `<span class="text-gray-400">${currentText[i]}</span>`;
        }
    }
    
    // Update the display
    practiceTextDisplayElement.innerHTML = displayHTML;

    // If all text is correct, load new practice content
    if (userInput === currentText) {
        setTimeout(() => {
            updatePracticeContent(); // Get the next text from the shuffled list
        }, 500); // 0.5 سېكۇنت كۈتۈش
    }
}

// Change practice type (words or sentences)
function changeType(type) {
    if (practiceData && (practiceData[type] || type === 'random')) {
        currentType = type;
        localStorage.setItem('practiceType', currentType);
        practiceIndex = 0; // Reset index when type changes
        updatePracticeContent();
    } else {
        console.error(`Invalid practice type selected: ${type}`);
        if (practiceTextDisplayElement) {
            practiceTextDisplayElement.textContent = 'Error: Invalid practice type.';
        }
        if (typingAreaElement) {
            typingAreaElement.value = '';
        }
        currentText = '';
        userInput = '';
        practiceIndex = 0;
    }
}

// Event listeners
document.addEventListener('DOMContentLoaded', () => {
    practiceTextDisplayElement = document.getElementById('practiceTextDisplay');
    typingAreaElement = document.getElementById('typingArea');
    practiceTypeSelectElement = document.getElementById('practiceTypeSidebar');

    // Wait a little for the data.js script to execute
    setTimeout(initializePracticeData, 100);
    
    if (typingAreaElement) {
        typingAreaElement.addEventListener('input', checkTyping);
    }

    if (practiceTypeSelectElement) {
        practiceTypeSelectElement.addEventListener('change', (event) => {
            changeType(event.target.value);
        });
        practiceTypeSelectElement.value = currentType;
    }
}); 